package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.ui.task.RegisterTask;
import com.xudow.app.ui.task.ResetPasswordTask;
import com.xudow.app.ui.task.VcodeTask;
import com.xudow.app.ui.widget.TitleBarTextView;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Forget password activity.
 *
 * @author lukecheng
 */
public class ForgetPasswordActivity extends BaseActivity {

    private EditText cellphoneEditText;
    private EditText passwordEditText;
    private EditText passwordAgainEditText;
    private EditText vcodeEditText;
    private Button resetBtn;
    //private LinearLayout vcodeSendBtn;
    private TextView vcodeText;
    private UserProfileWithOther user;
    /**
     * 验证码重新获取倒计时
     */
    private VcodeTask vcodeTask;
    private int vcodeCountDown = 60;
    private Timer vcodeTimer;
    private TimerTask vcodeTimerTask;

    private ResetPasswordTask resetPasswordTask;

    private void initVcodeTimerTask() {
        vcodeCountDown = 60;

        vcodeTimerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (vcodeCountDown <= 0) {
                            vcodeText.setClickable(true);
                            vcodeText.setText(getString(R.string.common_vcode_again));
                            vcodeTimerTask.cancel();
                        } else {
                            String countdownTxt = getString(R.string.common_vcode_countdown, vcodeCountDown);
                            vcodeText.setText(countdownTxt);
                        }

                        vcodeCountDown--;
                    }
                });
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        user=getMyApp().getProfile();
        cellphoneEditText = (EditText) findViewById(R.id.cellphone);
        passwordAgainEditText = (EditText) findViewById(R.id.password_again);
        passwordEditText = (EditText) findViewById(R.id.password);
        vcodeEditText = (EditText) findViewById(R.id.vcode);
        resetBtn = (Button) findViewById(R.id.reset_btn);

        //vcodeSendBtn = (LinearLayout) findViewById(R.id.vcode_send_btn);
        vcodeText = (TextView) findViewById(R.id.vcode_btn_txt);
        if(null!=user){
            cellphoneEditText.setText(user.getMobilePhone());
        }
        if (getIntent().getBooleanExtra("isChange", false)) {
            //如果是修改密码
            TitleBarTextView titleBarTextView = (TitleBarTextView) findViewById(R.id.title);
            titleBarTextView.setText(getString(R.string.title_activity_change_password));
        }
    }

    /**
     * 返回点击事件
     *
     * @param view
     */
    public void onBackBtnClick(View view) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (null != vcodeTask && !vcodeTask.isCancelled()) {
                vcodeTask.cancel(true);
                vcodeTask = null;
            }

            if (null != resetPasswordTask && !resetPasswordTask.isCancelled()) {
                resetPasswordTask.cancel(true);
                resetPasswordTask = null;
            }

            resetBtn.setEnabled(true);
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 确定按钮点击
     *
     * @param view
     */
    public void onResetClick(View view) {
        String cellphone = cellphoneEditText.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_format_err));
            return;
        }

        String password = passwordEditText.getText().toString().trim();
        if (StringUtils.isEmpty(password)) {
            passwordEditText.setError(getString(R.string.password_required));
            return;
        }

        String passwordAgain = passwordAgainEditText.getText().toString().trim();
        if (StringUtils.isEmpty(passwordAgain)) {
            passwordAgainEditText.setError(getString(R.string.password_not_match));
            return;
        }

        String vcode = vcodeEditText.getText().toString().trim();
        if (StringUtils.isEmpty(vcode)) {
            vcodeEditText.setError(getString(R.string.vcode_required));
            return;
        }

        HashMap<String, String> params = Maps.newHashMap();
        params.put("phone", cellphone);
        params.put("password", password);
        params.put("vcode", vcode);

        showLodingDialog(getString(R.string.processing));

        resetBtn.setEnabled(false);

        resetPasswordTask = new ResetPasswordTask(this, resetHandler);
        resetPasswordTask.execute(params);
    }

    /**
     * 获取验证码
     *
     * @param view
     */
    public void onGetVcodeClick(View view) {
        String cellphone = cellphoneEditText.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_format_err));
            return;
        }

        showLodingDialog(getString(R.string.common_vocde_send));

        HashMap<String, String> vcodeParams = Maps.newHashMap();
        vcodeParams.put("phone", cellphone);

        if (getIntent().getBooleanExtra("new_session", false)) {
            vcodeParams.put("login", "true");
        }

        vcodeParams.put("type", Config.VCODE_TYPE_FORGET_PASSWORD);

        vcodeTask = new VcodeTask(this, vcodeHandler);
        vcodeTask.execute(vcodeParams);
    }

    /**
     * 获取验证码Handler
     */
    private Handler vcodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (VcodeTask.SUCCESS == msg.what) {
                String vcodeSuccess = getString(R.string.common_vcode_success);
                getMyApp().makeToast(vcodeSuccess);
                vcodeText.setClickable(false);

                initVcodeTimerTask();
                vcodeTimer = new Timer();
                vcodeTimer.scheduleAtFixedRate(vcodeTimerTask, 1000, 1000);
            } else {
                String errVcode = getString(R.string.common_vcode_err);
                getMyApp().makeToast(errVcode);
            }
        }
    };

    /**
     * 登陆Handler
     */
    private Handler resetHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            resetBtn.setEnabled(true);

            switch (msg.what) {
                case RegisterTask.SUCCESS:
                    resetSuccess();
                    break;
                case RegisterTask.ERROR:
                case RegisterTask.ERROR_WITH_MESSAGE:
                    resetError(msg.getData());
                    break;
            }
        }
    };

    private void resetSuccess() {
        String successStr = getString(R.string.password_reset_success);
        Toast.makeText(this, successStr, Toast.LENGTH_LONG).show();
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    private void resetError(Bundle data) {
        String msg="";
        if (null != data && null != data.getString("errMessage")) {
            msg = data.getString("errMessage");
        } else {
            msg = getString(R.string.password_reset_fail);
        }
        getMyApp().makeToast(msg);
    }

}
